package com.atguigu.springcloud.controller;

import com.atguigu.springcloud.entity.CommonResult;
import com.atguigu.springcloud.entity.Payment;
import com.atguigu.springcloud.myloadbalancer.MyLoadBalancer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

@RequestMapping(("/consumer"))
@RestController
@Slf4j
public class ConsumeOrderController {

    @Resource
    private RestTemplate restTemplate;

    @Resource(name = "myloadbalancer2")
    private MyLoadBalancer myLoadBalancer;

    @Resource
    private DiscoveryClient discoveryClient;

    private static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";

    @PostMapping("/payment/create")
    @ResponseBody
    public CommonResult<Payment> create(@RequestBody Payment payment){
        return restTemplate.postForObject(PAYMENT_URL+"/create",payment,CommonResult.class);
    }

    @GetMapping("/getPaymentById/{id}")
    public CommonResult<Payment> getPayment(@PathVariable Long id){
        return restTemplate.getForObject(PAYMENT_URL+"/getPaymentById/"+id,CommonResult.class);
    }

    @GetMapping(value = "/getdiscovery")
    public CommonResult getdiscovery(){
        return restTemplate.getForObject(PAYMENT_URL+"/getdiscovery",CommonResult.class);
    }


    @GetMapping("/getPaymentById/{id}/getEntityPayment")
    public CommonResult<Payment> getEntityPayment(@PathVariable Long id){
        final ResponseEntity<CommonResult> forEntity = restTemplate.getForEntity(PAYMENT_URL + "/getPaymentById/" + id, CommonResult.class);
        if(forEntity.getStatusCode().is2xxSuccessful()){
            log.info(forEntity.getHeaders() + "\t" + forEntity.getStatusCodeValue() + "\t" + forEntity.getStatusCode());
            return forEntity.getBody();
        }else{
            return new CommonResult(404,"error");
        }
    }
    @GetMapping("/getlb")
    public String getlb(){
        final List<ServiceInstance> instances = discoveryClient.getInstances("cloud-payment-service");
        final ServiceInstance instance = myLoadBalancer.getInstance(instances);
        final URI uri = instance.getUri();
        return restTemplate.getForObject(uri+"/payment/getlb",String.class);
    }
}
